package com.kungfuhacking.wristbandpro.login.presenter;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.kungfuhacking.wristbandpro.base.bean.Basebean;
import com.kungfuhacking.wristbandpro.base.bean.RequestBean;
import com.kungfuhacking.wristbandpro.base.presenter.BasePresenter;
import com.kungfuhacking.wristbandpro.login.activity.LoginActivity;
import com.kungfuhacking.wristbandpro.login.bean.LoginBean;
import com.kungfuhacking.wristbandpro.login.view.IRegisterView;
import com.kungfuhacking.wristbandpro.login.activity.SetPwdActivity;
import com.kungfuhacking.wristbandpro.net.BaseNoTObserver;
import com.kungfuhacking.wristbandpro.net.RetrofitHttpUtil;
import com.kungfuhacking.wristbandpro.utils.Constant;
import com.kungfuhacking.wristbandpro.utils.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


/**
 * 注册页面presenter
 * Created by Aaron on 17/3/28.
 */

public class IRegisterPresenter implements BasePresenter {

    private IRegisterView iRegisterView;
    private String TAG = getClass().getSimpleName();

    public IRegisterPresenter(IRegisterView iRegisterView) {
        this.iRegisterView = iRegisterView;
    }

    public void getSmsCode() {

        String phoneNum = iRegisterView.getNum();
        if (TextUtils.isEmpty(phoneNum)) {
            iRegisterView.showErr("请输入手机号码");
            return;
        }

        if (phoneNum.length() != 11) {
            iRegisterView.showErr("请输入正确的手机号码");
            return;
        }

        LogUtil.e(TAG, "输入的手机号:" + phoneNum);

        getSmsFromNet(phoneNum);//获取验证码

    }

    /**
     * 获取验证码
     *
     * @param phoneNum 手机号码
     */
    private void getSmsFromNet(String phoneNum) {

        JSONObject j = new JSONObject();

        try {
            j.put("phoneNum", phoneNum);
            j.put("token", iRegisterView.getToken());
            j.put("type", Constant.GET_SMS_CODE_REGISTER);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        RetrofitHttpUtil.getInstance().getSms(new BaseNoTObserver<Basebean>() {

            @Override
            public void onSubscribe(Disposable d) {
                iRegisterView.showLoading("获取中...");
                compositeDisposable.add(d);
            }

            @Override
            public void onHandleSuccess(Basebean s) {
                iRegisterView.hideLoading();
                iRegisterView.showErr("请注意查收验证码");
                countDown();//倒计时
            }

            @Override
            public void onHandleError(String message) {
                iRegisterView.hideLoading();
                iRegisterView.showErr(message);
            }

            @Override
            public void onReLogin(String message) {
                iRegisterView.showErr(message);
                iRegisterView.hideLoading();
                iRegisterView.nextActivityWithSingleTask(LoginActivity.class);
            }
        }, new RequestBean().setData(j.toString()));

    }

    private Disposable countDisposable;

    private final int TIME = 60;

    /**
     * 倒计时
     */
    private void countDown() {

        iRegisterView.setUnclickable();//设置控件不可点击

        Observable.interval(0, 1, TimeUnit.SECONDS, AndroidSchedulers.mainThread()).map(new Function<Long, String>() {
            @Override
            public String apply(Long aLong) throws Exception {

//                LogUtil.d(TAG, "发送事件 " + aLong);

                if (aLong > TIME)
                    countDisposable.dispose();

                if (aLong == TIME) {
                    iRegisterView.setClickable();//设置控件可以点击
                    return "获取验证码";
                }

                return (TIME - aLong) + " 秒";
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        countDisposable = d;
                    }

                    @Override
                    public void onNext(String value) {
//                        LogUtil.d(TAG, "接受事件:" + value);
                        iRegisterView.setCountTime(value);
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtil.d(TAG, "事件错误" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private boolean nextStep() {

        String phoneNum = iRegisterView.getNum();
        if (TextUtils.isEmpty(phoneNum)) {
            iRegisterView.showErr("请输入手机号码");
            return false;
        }

        if (phoneNum.length() != 11) {
            iRegisterView.showErr("请输入正确的手机号码");
            return false;
        }

        if (TextUtils.isEmpty(iRegisterView.getCode())) {
            iRegisterView.showErr("请输入验证码");
            return false;
        }

        if (TextUtils.isEmpty(iRegisterView.getNickname())) {
            iRegisterView.showErr("请输入昵称");
            return false;
        }

        if (!iRegisterView.isAgree()) {
            iRegisterView.showErr("请阅读使用条款");
            return false;
        }

        return true;
    }


    /**
     * 提交验证
     */
    public void submitConfirm() {

        if (!nextStep())
            return;

        JSONObject j = new JSONObject();
        try {
            j.put("phoneNum", iRegisterView.getNum());
            j.put("nickName", iRegisterView.getNickname());
            j.put("msCode", iRegisterView.getCode());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RetrofitHttpUtil.getInstance().regCheckInfo(new BaseNoTObserver<LoginBean>() {

            @Override
            public void onSubscribe(Disposable d) {
                compositeDisposable.add(d);
                iRegisterView.showLoading("验证中...");
            }

            @Override
            public void onHandleSuccess(LoginBean s) {
                iRegisterView.hideLoading();
                //进入设置密码页面
                Bundle bundle = new Bundle();
                if (s != null && s.getToken() != null) {
                    Log.d(TAG, "注册时的 TOKEN :" + s.getToken().getToken());
                    bundle.putString("token", s.getToken().getToken());
                    bundle.putString("tel", iRegisterView.getNum());
                    iRegisterView.nextActivityWithBundle(SetPwdActivity.class, bundle);
                } else
                    iRegisterView.showErr("数据错误");
            }

            @Override
            public void onHandleError(String message) {
                iRegisterView.showErr(message);
                iRegisterView.hideLoading();
            }

            @Override
            public void onReLogin(String message) {
                iRegisterView.showErr(message);
                iRegisterView.hideLoading();
                iRegisterView.nextActivityWithSingleTask(LoginActivity.class);
            }
        }, new RequestBean().setData(j.toString()));

    }

    @Override
    public void clearRequest() {
        LogUtil.d(TAG, " ~~~ 取消网络请求 ~~~ ");
        compositeDisposable.clear();

    }
}
